package com.Timer {
	import com.debug.TDebug;
	
	import flash.display.Shape;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getTimer;

	/**按侦速来写时间(如需要临时变量不被回收，请把_shape变为静态变量即可)
	 * @author pethan
	 */
	public class FrameTimer extends EventDispatcher {
		//延时的时间（请大于42毫秒)
		public var delay:Number;
		//重复的次数(为0将会一直重复)
		public var repeatCount:int;
		
		private var lastTime:Number=0;
		
		public var currentCount:int=0;
		
		private var run : Boolean=false;
		private  var _shape:Shape=new Shape();
		
		
		/**
		 * 按侦速来写时间
		 * @param delay 以毫秒为单位，请大于42的值
		 * @param repeatCount 重复的次数，如为0就一直重复下去
		 * 
		 */		
		public function FrameTimer(delay:Number,repeatCount:int=0):void{
			this.delay=delay;
			this.repeatCount = repeatCount;
		}
		
		private function onEnterFrame(event:Event):void {
			var currentTime:int=getTimer();
			var diffTiime:int=currentTime-lastTime;
			if(diffTiime>=delay){
				this.currentCount++;
				var count : int = diffTiime/delay;
				//延时的次数全部加上去
				lastTime += delay*count;
				for(var i:int=0;i<count;i++){
					onTimer();
					if(this.currentCount==repeatCount&&run&&repeatCount!=0){/*当前是可以运行的,因为有时候onIimer完成,就被重置,会倒是错误*/
						this.reset();
						this.onComplete();
						break;
					}
				}
			}
		}
		
		/*
		 * 开始计时
		 */
		public function start():void{
	//		TDebug.trace('计时开始');
			run=true;
			lastTime=getTimer();
			_shape.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		
		/*
		 * 停止计时
		 */
		public function stop():void{
		//	TDebug.trace('计时结束');
			run=false;
			if(this._shape.hasEventListener(Event.ENTER_FRAME)){
				this._shape.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			}
		}
		
		/*
		 * 时间重置
		 */
		public function reset():void{
			this.currentCount=0;
			this.stop();
		}
		
		//完成
		private function onComplete():void{
			this.stop();
			this.dispatchEvent(new FrameTimerEvent(FrameTimerEvent.TIMER_COMPLETE));
		}
		
		private function onTimer():void{
			this.dispatchEvent(new FrameTimerEvent(FrameTimerEvent.TIMER));
		}
		
		/*
		 * 当前的计时器是否在计时
		 */
		public function get running() : Boolean{
			return this.run;
		}
		
		public function dispose():void{
			this.stop();
			_shape=null;
		}
	}
}
